package com.newtouch.bxzs.business.personal.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newtouch.bxzs.business.personal.mapper.CommonProblemMapper;
import com.newtouch.bxzs.business.personal.model.CommonProblemBO;
import com.newtouch.bxzs.business.personal.model.CommonProblemVO;
import com.newtouch.bxzs.business.personal.model.EnableCommonProblemVO;
import com.newtouch.bxzs.business.personal.model.ModifyCommonProblemVO;
import com.newtouch.bxzs.business.personal.service.CommonProblemService;
import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.em.ButtonTypeEnum;
import com.newtouch.bxzs.common.base.em.PublishStatusEnum;
import com.newtouch.bxzs.common.base.em.UserFlagEnum;
import com.newtouch.bxzs.common.base.model.CommonProblem;
import com.newtouch.bxzs.common.base.model.bo.DataDictionaryValueBO;
import com.newtouch.bxzs.common.base.util.RedisUtils;
import com.newtouch.bxzs.common.base.util.UserDetailUtil;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;

/**
 * 常见问题服务实现类
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2020年12月31日</td>
 * <td>xiongdianqiang</td>
 * <td>Create</td>
 * </tr>
 * </table>
 * 
 * @author xiongdianqiang
 * 
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
public class CommonProblemServiceImpl implements CommonProblemService {

	@Autowired
	private CommonProblemMapper commonProblemMapper;
	@Autowired
	private RedisUtils redisUtils;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.business.personal.service.CommonProblemsService#
	 * getCommonProblemList(com.newtouch.bxzs.business.personal.model.
	 * CommonProblemVO)
	 */
	@Override
	public Map<String, Page<CommonProblemBO>> getCommonProblemList(CommonProblemVO commonProblemVO) {
		if (commonProblemVO == null) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		if (commonProblemVO.getUserFlag() == null) {
			throw new BaseException("客户端请求标志不能为空！");
		}
		// 通过redis获取常见问题分类
		List<DataDictionaryValueBO> dataDictionaryEntryList = JSONArray
				.parseArray(redisUtils.get("PROBLEM_COMMON_TYPE"), DataDictionaryValueBO.class);
		// 实例化一个QueryWrapper
		QueryWrapper<CommonProblem> queryWrapper = new QueryWrapper<CommonProblem>();
		// 根据问题描述模糊查询
		if (commonProblemVO.getProblemCommonDescription() != null) {
			queryWrapper.like("PROBLEM_COMMON_DESCRIPTION", commonProblemVO.getProblemCommonDescription());
		}
		// 根据问题分类查询或PC端访问
		if (commonProblemVO.getProblemCommonType() != null
				|| commonProblemVO.getUserFlag().equals(UserFlagEnum.PC_FLAG.getCode())) {
			// APP端按照问题分类查询，PC端返回所有分页
			if (commonProblemVO.getUserFlag().equals(UserFlagEnum.APP_FLAG.getCode())) {
				queryWrapper.eq("PROBLEM_COMMON_TYPE", commonProblemVO.getProblemCommonType());
			}
			// 根据创建时间倒叙排列
			queryWrapper.orderByDesc("UPDATE_TIME");
			// 分页查询CommonProblem
			Page<CommonProblem> page = new Page<>();
			page.setCurrent(commonProblemVO.getCurrentPage());
			page.setSize(commonProblemVO.getPageSize());
			Page<CommonProblem> CommonProblemPage = commonProblemMapper.selectPage(page, queryWrapper);
			List<CommonProblem> CommonProblemList = CommonProblemPage.getRecords();
			if (CommonProblemList == null) {
				return null;
			}
			// 将CommonProblemList转换为CommonProblemBOList
			List<CommonProblemBO> CommonProblemBOList = new ArrayList<CommonProblemBO>();
			for (CommonProblem CommonProblem : CommonProblemList) {
				CommonProblemBO CommonProblemBO = new CommonProblemBO();
				BeanUtil.copyProperties(CommonProblem, CommonProblemBO);
				CommonProblemBOList.add(CommonProblemBO);
			}
			// 将CommonProblemBO转换为分页返回结果
			Page<CommonProblemBO> CommonProblemBOPage = new Page<CommonProblemBO>();
			CommonProblemBOPage.setCurrent(CommonProblemPage.getCurrent());
			CommonProblemBOPage.setSize(CommonProblemPage.getSize());
			CommonProblemBOPage.setPages(CommonProblemPage.getPages());
			CommonProblemBOPage.setTotal(CommonProblemPage.getTotal());
			CommonProblemBOPage.setRecords(CommonProblemBOList);
			// 返回分页map
			Map<String, Page<CommonProblemBO>> pageMap = new HashMap<String, Page<CommonProblemBO>>();
			if (commonProblemVO.getUserFlag().equals(UserFlagEnum.PC_FLAG.getCode())) {
				// pc返回分页map
				pageMap.put(String.valueOf(UserFlagEnum.PC_FLAG), CommonProblemBOPage);
			} else {
				// app返回分页map，key为字典项名称
				if (dataDictionaryEntryList != null) {
					for (DataDictionaryValueBO dataDictionaryEntry : dataDictionaryEntryList) {
						if (commonProblemVO.getProblemCommonType()
								.equals(dataDictionaryEntry.getDataDictionaryEntryValue())) {
							pageMap.put(dataDictionaryEntry.getDataDictionaryEntryName(), CommonProblemBOPage);
						}
					}
				}
			}
			return pageMap;
			// APP端没有传问题分类参数，则返回每个分类的10条分页数据
		} else {
			// 存入map中
			Map<String, Page<CommonProblemBO>> map = new HashMap<String, Page<CommonProblemBO>>();
			if (dataDictionaryEntryList != null) {
				for (DataDictionaryValueBO dataDictionaryEntry : dataDictionaryEntryList) {
					QueryWrapper<CommonProblem> wrapper = new QueryWrapper<CommonProblem>();
					if (commonProblemVO.getProblemCommonDescription() != null) {
						wrapper.like("PROBLEM_COMMON_DESCRIPTION", commonProblemVO.getProblemCommonDescription());
					}
					// 根据创建时间倒叙排列
					wrapper.orderByDesc("UPDATE_TIME");
					String dataDictionaryEntryValue = dataDictionaryEntry.getDataDictionaryEntryValue();
					String dataDictionaryEntryName = dataDictionaryEntry.getDataDictionaryEntryName();
					wrapper.eq("PROBLEM_COMMON_TYPE", dataDictionaryEntryValue);
					Page<CommonProblem> page = new Page<CommonProblem>(1, 10);
					Page<CommonProblem> selectPage = commonProblemMapper.selectPage(page, wrapper);
					List<CommonProblem> CommonProblemList = selectPage.getRecords();
					if (CommonProblemList == null) {
						return null;
					}
					// 将CommonProblemList转换为CommonProblemBOList
					List<CommonProblemBO> CommonProblemBOList = new ArrayList<CommonProblemBO>();
					for (CommonProblem CommonProblem : CommonProblemList) {
						CommonProblemBO CommonProblemBO = new CommonProblemBO();
						BeanUtil.copyProperties(CommonProblem, CommonProblemBO);
						CommonProblemBOList.add(CommonProblemBO);
					}
					// 将CommonProblemBO转换为分页返回结果
					Page<CommonProblemBO> CommonProblemBOPage = new Page<CommonProblemBO>();
					CommonProblemBOPage.setCurrent(selectPage.getCurrent());
					CommonProblemBOPage.setSize(selectPage.getSize());
					CommonProblemBOPage.setPages(selectPage.getPages());
					CommonProblemBOPage.setTotal(selectPage.getTotal());
					CommonProblemBOPage.setRecords(CommonProblemBOList);
					map.put(dataDictionaryEntryName, CommonProblemBOPage);
				}
			}
			return map;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.business.personal.service.CommonProblemService#
	 * getCommonProblemDetail(java.lang.String)
	 */
	@Override
	public CommonProblemBO getCommonProblemDetail(String problemCommonId) {
		if (StringUtils.isEmpty(problemCommonId)) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		CommonProblem commonProblem = commonProblemMapper.selectById(problemCommonId);
		if (!BeanUtil.isEmpty(commonProblem)) {
			CommonProblemBO commonProblemBO = new CommonProblemBO();
			BeanUtil.copyProperties(commonProblem, commonProblemBO);
			return commonProblemBO;
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.business.personal.service.CommonProblemService#
	 * modifyCommonProblem(com.newtouch.bxzs.business.personal.model.
	 * ModifyCommonProblemVO)
	 */
	@Override
	public String modifyCommonProblem(ModifyCommonProblemVO modifyCommonProblemVO) {
		if (modifyCommonProblemVO == null) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		// 校验必录项
		if (StringUtils.isEmpty(modifyCommonProblemVO.getProblemCommonDescription())
				|| StringUtils.isEmpty(modifyCommonProblemVO.getProblemCommonType())
				|| StringUtils.isEmpty(modifyCommonProblemVO.getProblemCommonAnswerDescription())) {
			throw new BaseException("必录项未填写！");
		}
		// 校验描述字符长度
		if (!StringUtils.isEmpty(modifyCommonProblemVO.getProblemCommonDescription())
				&& modifyCommonProblemVO.getProblemCommonDescription().length() > 300) {
			throw new BaseException("问题描述字符长度不能超过300！");
		}
		// 校验答案字符长度
		if (!StringUtils.isEmpty(modifyCommonProblemVO.getProblemCommonAnswerDescription())
				&& modifyCommonProblemVO.getProblemCommonAnswerDescription().length() > 3000) {
			throw new BaseException("问题答案字符长度不能超过3000！");
		}
		// 点击取消按钮（3），不做任何操作
		if (modifyCommonProblemVO.getButtonType().equals(ButtonTypeEnum.REVOKE_BUTTON.getCode())) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		CommonProblem problem = commonProblemMapper.selectById(modifyCommonProblemVO.getProblemCommonId());
		CommonProblem commonProblem = new CommonProblem();
		// 新增
		if (BeanUtil.isEmpty(problem)) {
			commonProblem.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
			commonProblem.setCreateTime(new Date());
			commonProblem.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
			commonProblem.setUpdateTime(new Date());
			commonProblem.setProblemCommonType(modifyCommonProblemVO.getProblemCommonType());
			commonProblem.setProblemCommonDescription(modifyCommonProblemVO.getProblemCommonDescription());
			commonProblem.setProblemCommonAnswerDescription(modifyCommonProblemVO.getProblemCommonAnswerDescription());
			commonProblem.setDeleteFlag(false);
			// 点击暂存按钮（1）
			if (modifyCommonProblemVO.getButtonType().equals(ButtonTypeEnum.TEMPORARY_BUTTON.getCode())) {
				// 问题状态为未发布
				commonProblem.setPublishStatus(PublishStatusEnum.UNPUBLISH_STATUS.getResultCode());
			}
			// 点击的是发布按钮（2）
			else {
				// 调用短信验证接口，通过之后发布
				// 问题状态为已发布
				commonProblem.setPublishStatus(PublishStatusEnum.PUBLISHED_STATUS.getResultCode());
			}
			commonProblemMapper.insert(commonProblem);
			return commonProblem.getProblemCommonId();
		} else {// 修改
			BeanUtil.copyProperties(modifyCommonProblemVO, problem);
			// 点击暂存按钮（1）
			if (modifyCommonProblemVO.getButtonType().equals(ButtonTypeEnum.TEMPORARY_BUTTON.getCode())) {
				// 问题状态为未发布
				problem.setPublishStatus(PublishStatusEnum.UNPUBLISH_STATUS.getResultCode());
			}
			// 点击的是发布按钮（2）
			else {
				// 调用短信验证接口，通过之后发布
				// 问题状态为发布
				problem.setPublishStatus(PublishStatusEnum.PUBLISHED_STATUS.getResultCode());
			}
			commonProblemMapper.updateById(problem);
		}
		return problem.getProblemCommonId();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.business.personal.service.CommonProblemService#
	 * deleteCommonProblem(java.lang.String)
	 */
	@Override
	public void deleteCommonProblem(List<String> problemCommonIds) {
		if (CollectionUtil.isEmpty(problemCommonIds)) {
			throw new BaseException("集合为空，删除失败");
		}
		// 如果是已发布的，则不能删除
		QueryWrapper<CommonProblem> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("PROBLEM_COMMON_ID", problemCommonIds);
		queryWrapper.eq("PUBLISH_STATUS", PublishStatusEnum.PUBLISHED_STATUS.getResultCode());
		List<CommonProblem> selectList = commonProblemMapper.selectList(queryWrapper);
		if (!CollectionUtil.isEmpty(selectList)) {
			throw new BaseException(BaseErrorEnum.PUBLISH_STATUS);
		}
		// 设置修改人和修改时间
		QueryWrapper<CommonProblem> updateQuery = new QueryWrapper<>();
		updateQuery.in("PROBLEM_COMMON_ID", problemCommonIds);
		CommonProblem commonProblem = new CommonProblem();
		commonProblem.setUpdateTime(new Date());
		commonProblem.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
		commonProblemMapper.update(commonProblem, updateQuery);
		// 批量逻辑删除
		commonProblemMapper.deleteBatchIds(problemCommonIds);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.business.personal.service.CommonProblemService#
	 * enableCommonProblem(java.lang.String)
	 */
	@Override
	public void enableCommonProblem(EnableCommonProblemVO enableCommonProblemVO) {
		String problemCommonId = enableCommonProblemVO.getProblemCommonId();
		if (StringUtils.isEmpty(enableCommonProblemVO)) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		CommonProblem commonProblem = commonProblemMapper.selectById(problemCommonId);
		if (!BeanUtil.isEmpty(commonProblem)) {
			// 1未发布,2已发布,3已结束,4已取消,5已撤销
			// 当前为已发布状态
			if (commonProblem.getPublishStatus().equals(PublishStatusEnum.PUBLISHED_STATUS.getResultCode())) {
				if (ButtonTypeEnum.PUBLIC_BUTTON.getCode().equals(enableCommonProblemVO.getOperationButton())) {
					throw new BaseException("已发布，不可再次发布！");
				} else {
					// 撤销成功！
					commonProblem.setPublishStatus(PublishStatusEnum.REVOKED_STATUS.getResultCode());
					commonProblemMapper.updateById(commonProblem);
				}
				// 当前为已撤销状态
			} else if (commonProblem.getPublishStatus().equals(PublishStatusEnum.REVOKED_STATUS.getResultCode())) {
				if (ButtonTypeEnum.REVOKE_BUTTON.getCode().equals(enableCommonProblemVO.getOperationButton())) {
					throw new BaseException("已撤销，不可再次撤销！");
				} else {
					// 发布成功
					commonProblem.setPublishStatus(PublishStatusEnum.PUBLISHED_STATUS.getResultCode());
					commonProblemMapper.updateById(commonProblem);
				}
				// 当前为未发布状态
			} else {
				if (ButtonTypeEnum.REVOKE_BUTTON.getCode().equals(enableCommonProblemVO.getOperationButton())) {
					throw new BaseException("未发布，不可撤销！");
				} else {
					// 发布成功
					commonProblem.setPublishStatus(PublishStatusEnum.PUBLISHED_STATUS.getResultCode());
					commonProblemMapper.updateById(commonProblem);
				}
			}
		}
	}

}
